package com.itsu.commons.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.io.IOException;
import java.util.Properties;

public class SendSmsUtil {

    private static String regionId;
    private static String key;
    private static String secret;

    static {
        Properties properties = new Properties();
        try {
            properties.load(SendSmsUtil.class.getClassLoader().getResourceAsStream("alibabaServer.properties"));
            regionId = properties.getProperty("sms.region_id");
            key = properties.getProperty("sms.access_key_id");
            secret = properties.getProperty("sms.access_key_secret");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static boolean sendSms(String phone, String validatorCode) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, key, secret);
        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Token
         **/
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("SignName", "杭州黑马传智健康");
        request.putQueryParameter("TemplateCode", "SMS_184110818");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+validatorCode+"\"}");
        request.putQueryParameter("PhoneNumbers", phone);
        try {
            CommonResponse response = client.getCommonResponse(request);
            if (response.getData().contains("\"Message\":\"OK\"")) {
                return true;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return false;
    }
}
